package cn.com.okgotest.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.github.jlmd.animatedcircleloadingview.AnimatedCircleLoadingView;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.leon.lfilepickerlibrary.utils.Constant;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.com.okgo.OkGo;
import cn.com.okgo.callback.HttpStringCallback;
import cn.com.okgo.model.Bytes;
import cn.com.okgotest.R;
import cn.com.okgotest.fragment.base.BaseFragment;
import cn.com.okgotest.utils.BitmapUtils;

import static android.app.Activity.RESULT_OK;

public class PostFragment extends BaseFragment implements View.OnClickListener {

    private static final int KEY_REQUESTCODE_FROM_ACTIVITY = 1000;

    private TextView pathTv;
    private Button postBtn;
    private AnimatedCircleLoadingView progressBar;
    private List<String> fileList = new ArrayList<>();
    private List<LocalMedia> imageList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate( R.layout.fragment_post, container, false );
        init( view );
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        fileList.clear();
        imageList.clear();
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case KEY_REQUESTCODE_FROM_ACTIVITY:
                    fileList = data.getStringArrayListExtra( "paths" );
                    pathTv.setText( fileList.get( 0 ) );
                    postBtn.setEnabled( true );
                case PictureConfig.CHOOSE_REQUEST:
                    imageList = PictureSelector.obtainMultipleResult( data );
                    pathTv.setText( imageList.size() + "" );
                    postBtn.setEnabled( true );
                    break;
            }

        }
    }

    private void init(View view) {
        Button button = view.findViewById( R.id.button );
        Button button1 = view.findViewById( R.id.button1 );
        postBtn = view.findViewById( R.id.postBtn );
        pathTv = view.findViewById( R.id.pathTv );
        progressBar = view.findViewById( R.id.progressBar );
        button.setOnClickListener( this );
        button1.setOnClickListener( this );
        postBtn.setOnClickListener( this );
        postBtn.setEnabled( false );
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.button:
                new LFilePicker()
                        .withActivity( getActivity() )
                        .withRequestCode( KEY_REQUESTCODE_FROM_ACTIVITY )
                        .withIconStyle( Constant.ICON_STYLE_BLUE )
                        .withMutilyMode( true ) //多选
                        .withFileFilter( new String[]{".jpg", ".jpeg", ".png"} ) // 文件类型
                        .start();
                break;

            case R.id.button1:

                Log.e( "PostFragment", "选择图片" );

                PictureSelector.create( getActivity() )
                        .openGallery( PictureMimeType.ofImage() )//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()
                        .maxSelectNum( 4 )
                        .imageSpanCount( 3 )// 每行显示个数 int
                        .selectionMode( PictureConfig.MULTIPLE )//多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage( true )// 是否可预览图片
                        .isCamera( true )
                        .selectionMedia( imageList )
                        .forResult( PictureConfig.CHOOSE_REQUEST );//结果回调onActivityResult code

                break;

            case R.id.postBtn:
                postBtn.setEnabled( false );
                startDeterminate( progressBar );
                progressBar.setPercent( 0 );
                if (fileList.size() > 0) {
                    uploadFile();
                } else if (imageList.size() > 0) {
                    uploadImage();
                }
                break;
        }
    }

    private void uploadFile() {
        String path = pathTv.getText().toString();
        if (TextUtils.isEmpty( path )) {
            Toast.makeText( getActivity(), "请选择文件", Toast.LENGTH_SHORT ).show();
            return;
        }


        OkGo.post( "http://10.19.48.210:8080/TomcatTest/upload" )
                .upFile( "file", new File( path ) )
                .params( "content", "content" )
                .execute( new HttpStringCallback() {
                    @Override
                    public void onSuccess(String obj, String baseUrl) {
                        postBtn.setEnabled( true );
                        progressBar.stopOk();
                    }

                    @Override
                    public void onFailed(Exception e, String baseUrl) {
                        postBtn.setEnabled( true );
                        progressBar.stopFailure();
                    }

                    @Override
                    public void onUpLoadProgress(long progress, long total) {
                        progressBar.setPercent( (int) (progress * 100 / total) );
                    }
                } );
    }

    private void uploadImage() {

//        Map<String, File> map = new HashMap<>();
//        for (int i = 0; i < imageList.size(); i++) {
//            LocalMedia media = imageList.get(i);
//            Log.e( "PostFragment", media.getPath() );
//            map.put( "img" + (i + 1), new File(media.getPath()) );
//        }


        List<Bytes> list = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            Bytes postByte = new Bytes();
            LocalMedia media = imageList.get( i );
            ByteArrayOutputStream baos = BitmapUtils.getScaleBitMapBoas( media.getPath(), 100 );
            File file = new File( media.getPath() );
            postByte.bytes = baos.toByteArray();
            postByte.key = "img" + (i + 1);
            postByte.fileName = file.getName();
            list.add( postByte );

            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        OkGo.post( "http://os7.ngrok.cc/api/system/feedback/addnew" )
                .upBytes( list )
                .params( "user_id", "0" )
                .params( "device_id", "866500022869178" )
                .params( "feedback", "我要吐槽吐槽吐槽吐槽吐槽" )
                .params( "appid", "zxjt_client" )
                .params( "phone_model", "MI 4LTE" )
                .params( "os_type", "android" )
                .params( "os_version", "6.0.1" )
                .params( "app_type", "66099" )
                .params( "app_version", "2.5.0" )
                .params( "phone_number", "" )
                .params( "QQ_number", "1234567" )
                .execute( new HttpStringCallback() {
                    @Override
                    public void onSuccess(String obj, String baseUrl) {
                        PictureFileUtils.deleteCacheDirFile( getActivity() );
                        postBtn.setEnabled( true );
                        progressBar.stopOk();
                    }

                    @Override
                    public void onFailed(Exception e, String baseUrl) {
                        PictureFileUtils.deleteCacheDirFile( getActivity() );
                        postBtn.setEnabled( true );
                        progressBar.stopFailure();
                    }

                    @Override
                    public void onUpLoadProgress(long progress, long total) {
                        progressBar.setPercent( (int) (progress * 100 / total) );
                    }
                } );

    }
}
